package com.homelink.crashhandle;

import android.content.Context;
import android.content.Intent;
import com.homelink.crashhandle.service.UploadFileService;
import com.homelink.crashhandle.util.ConstantsUtils;

import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * Created by Fcy on 2015/10/30.<br/>
 * 自定义处理系统未捕获的crash
 */
public class MyCrashHandler implements Thread.UncaughtExceptionHandler
{
	private static MyCrashHandler mCatchHandler = new MyCrashHandler();
	private Thread.UncaughtExceptionHandler mDefaultHandler;

	private Context mContext;

	private MyCrashHandler()
	{
	}

	public static MyCrashHandler getInstance()
	{
		return mCatchHandler;
	}

	public void init(Context context)
	{
		mContext = context;
		mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
		Thread.setDefaultUncaughtExceptionHandler(this);
	}

	public void uncaughtException(Thread thread, Throwable ex)
	{
		LogBuffer.getInstance().writeLog();
		LogBuffer.getInstance().write(obtainExceptionInfo(ex));
		// 打压缩包，名称为当前时间
		LogBuffer.getInstance().post();
		Intent intent = new Intent(mContext, UploadFileService.class);
		// 标识是发生crash自动上传还是用户主动上传
		intent.putExtra(ConstantsUtils.IS_CRASH, true);
		mContext.startService(intent);

		// 抛出
		mDefaultHandler.uncaughtException(thread, ex);
	}

	/**
	 * 获取系统未捕捉的错误信息
	 *
	 * @param throwable
	 * @return
	 */
	private String obtainExceptionInfo(Throwable throwable)
	{
		StringWriter mStringWriter = new StringWriter();
		PrintWriter mPrintWriter = new PrintWriter(mStringWriter);
		throwable.printStackTrace(mPrintWriter);
		mPrintWriter.close();
		return mStringWriter.toString();
	}
}
